<template>
  <div class="hawkContent">
    <hawk-breadcrumb></hawk-breadcrumb>
    <el-row :gutter="20">
      <el-col :span="4" style="display:flex;align-items:center;">
        <span style="color: #666666; font-size: 13px;">机房名称：</span>
        <el-input placeholder="请输入机房名称"
                  v-model="queryForm.query.computeRoomName" style="flex:1;">
        </el-input>
      </el-col>
      <el-col :span="4" style="display:flex;align-items:center;">
        <span style="color: #666666; font-size: 13px;">地区：</span>
        <el-select clearable v-model="queryForm.query.areaId"
                   placeholder="请选择地区" style="flex:1;">
          <el-option v-for="item in search_areaList" :key="item.id"
                     :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4" style="display:flex;align-items:center;">
        <span style="color: #666666; font-size: 13px;">公司：</span>
        <el-select clearable v-model="queryForm.query.companyId"
                   placeholder="请选择公司" style="flex:1;">
          <el-option v-for="item in search_companyList" :key="item.id"
                     :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4" style="display:flex;align-items:center;">
        <span style="color: #666666; font-size: 13px;">部门：</span>
        <el-select clearable v-model="queryForm.query.deptId"
                   placeholder="请选择部门" style="flex:1;">
          <el-option v-for="item in search_departmentList" :key="item.id"
                     :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-col>

      <el-col style="min-width: 9%;max-width:13%" :span="4">
        <el-button type="hawkSearch" @click="search()">搜索</el-button>
        <el-button plain @click="reSet()">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right; text-align: right; padding-right: 30px">
        <el-button type="hawkCreate" @click="editRoom()">创建机房</el-button>
      </el-col>
    </el-row>
    <hawk-table :table-data="tableData" v-model="multipleSelection"
                :page="queryForm.page" :number=true :options="[
        { key: 'name', label: '机房名称',width:'130' },
        { key: 'number', label: '机房编号',width:'100' },
        { key: 'company', label: '公司' ,width:'130'},
        { key: 'department', label: '部门' ,width:'100'},
        { key: 'area', label: '地区' ,width:'90'},
        { key: 'address', label: '地址' ,width:'130'},
        { key: 'sysUser', label: '负责人' ,width:'100'},
        { key: 'sysUserMobile', label: '联系电话' ,width:'100'},
        { key: 'handle', label: '操作' ,width:'150'}
      ]">

      <template #company="{ row }">
        <span>{{row.company?row.company.name:""}}</span>
      </template>

      <template #department="{ row }">
        <span>{{row.department?row.department.name:""}}</span>
      </template>
      <template #area="{ row }">
        <span>{{row.area?row.area.name:""}}</span>
      </template>
      <template #sysUser="{ row }">
        <span>{{row.sysUser?row.sysUser.nickName:""}}</span>
      </template>
      <template #sysUserMobile="{ row }">
        <span>{{row.sysUser?row.sysUser.mobile:""}}</span>
      </template>

      <template #handle="{ row }">
        <span class="hawk-text-btn" @click="editRoom(row)">编辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="deleteRoom(row)">删除</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="goTuopu(row)">查看视图</span>
      </template>
    </hawk-table>
    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="catchDelete()">批量删除</el-button>
        <!-- <el-button plain>导出</el-button> -->
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryForm.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryForm.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="formTitle" :visible.sync="addDialogVisible"
               :close-on-click-modal="false" @close="addDialogClosed">

      <!-- 内容主题区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"
               label-position="right" label-width="100px">

        <el-form-item label="机房名称" prop="name">
          <el-input :readonly="formTitle == '查看机房'" v-model="addForm.name">
          </el-input>
        </el-form-item>

        <el-form-item ref="roomNumber" label="机房编号" prop="number">
          <!-- :disabled="Boolean(this.addForm.id)" -->
          <el-input v-model="addForm.number"></el-input>
        </el-form-item>

        <el-form-item label="地区" prop="areaId">
          <!-- :disabled="Boolean(this.addForm.id)" -->
          <el-select clearable @change="areaChange" v-model="addForm.areaId"
                     placeholder="请选择地区">
            <el-option v-for="item in areaList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="公司" prop="companyId">
          <el-select clearable v-model="addForm.companyId" @change="areaChange" placeholder="请选择公司"
                     style="flex:1;">
            <el-option v-for="item in companyList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select clearable v-model="addForm.deptId" placeholder="请选择部门"
                     style="flex:1;">
            <el-option v-for="item in departmentList" :key="item.id"
                       :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address"></el-input>
        </el-form-item>

        <el-form-item label="负责人" prop="userId">
          <el-select clearable v-model="addForm.userId" placeholder="请选择负责人">
            <el-option v-for="item in principalList" :key="item.id"
                       :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog()">取 消</el-button>
        <el-button type="primary" @click="saveRoom()">确 定</el-button>
      </span>

    </el-dialog>
  </div>
</template>

<script>
/**
 * @author  肖帅
 * @description 机房视图容器
 * @api /cmdb-hhome
 * @since 2021-10-12 15:30
 * @update
 * @modifier
 * @bug 无
 * @version v1.0.1
 */
import {
  queryComputerRoom,
  doDelete,
  doAdd,
  doEdit,
  isRoomNumExists
} from '@/api/assets/list/computerRoom'

import { getAll as getAreaList } from '@/api/assets/dictionaries/area'

import { getAll as getCompanyList, getComByAreaId } from '@/api/assets/dictionaries/company'

import { getAll as getDepartmentList, getDepartByComId } from '@/api/assets/dictionaries/department'

import { getPeopleByDepartId } from '@/api/system/user'

import { getAllComUser } from '@/api/user.js'



import { getList as getCIList } from '@/api/assets/ci/room'


export default {
  //import引入的组件需要注入到对象中才能使用",
  data () {

    let isHaveNumber = async (rule, value, callback) => {

      console.log("-----isHaveNumber----");
      if (this.addForm.id) {
        // 编辑状态
        // 编辑的时候，所选  编号\地区\ 公司，还是以前的，不做校验
        if (this.cacheNumberAreaId.number == value 
        && this.cacheNumberAreaId.areaId == this.addForm.areaId
        && this.cacheNumberAreaId.companyId == this.addForm.companyId
        
        ) {
          callback()
          return
        }
      }

      // 没有写完，不处理
      if (!this.addForm.areaId || !this.addForm.companyId) {
        // callback('请先选择地区、同一地区下编号唯一')
        callback()
        return
      }

      value = this.addForm.number

      console.log(value);
      let ret = await isRoomNumExists({
        number: value,
        areaId: this.addForm.areaId,
        companyId: this.addForm.companyId
      })

      console.log(ret , '-------判断机房是否存在----------');
      if (ret) {
        callback('该地区编号已存在')
      } else {
        callback()
      }

    }

    //这里存放数据",
    return {
      cacheNumberAreaId: {
        number: '',
        areaId: '',
        companyId: '',
      },
      //----------弹出的对话框中所需要的变量----------------
      // 公司列表
      companyList: [],
      // 部门列表
      departmentList: [],
      // 负责人列表
      principalList: [],
      // 地区列表
      areaList: [],

      //-----------主页面搜索框中的变量-------------------
      search_companyList: [],
      // 部门列表
      search_departmentList: [],
      // 负责人列表
      search_principalList: [],
      // 地区列表
      search_areaList: [],

      //-----------------

      // 表单标题
      formTitle: '',
      addDialogVisible: false,
      // 多选数据
      multipleSelection: [],
      // 添加机房时的  提交数据
      addForm: {
        name: '',
        number: '', // 编号
        companyId: '',
        deptId: '',
        address: '',
        areaId: '',
        userId: ''
      },
      /**
       * 新建机房的 问题，，哪些是选择的，，哪些是 输入的
       */
      addFormRules: {
        name: [
          { required: true, message: '请输入机房名称', trigger: 'blur' },
          { min: 3, max: 20, message: '机房名称的长度在3-20个字符之间', trigger: 'blur', }
        ],
        'number': [
          { required: true, message: '请输入机房编号', trigger: 'blur' },
          { validator: isHaveNumber, trigger: 'blur' },
        ],
        areaId: [
          { required: true, message: '请选择地区', trigger: 'change' },
        ],
        companyId: [
          { required: true, message: '请选择公司名称', trigger: 'blur' },
        ],
        "deptId": [
          { required: true, message: '部门名称', trigger: 'blur' },
        ],
        address: [
          { required: true, message: '地址', trigger: 'blur' },
        ],
        // userId: [
        //   { required: true, message: '负责人', trigger: 'change' },
        // ],

      },
      tableData: [],
      total: 0,
      // 查询机房时所需要的数据
      queryForm: {
        query: {
          computeRoomName: '',
          companyId: '',
          deptId: '',
          areaId: '',
          principalName: "" // 接口有需要，但页面中没有输入的地方
        },
        page: {
          current: 1,
          size: 10
        }
      },

      ciRoomList: [], // 有视图的机房列表

      isFirstEdit: false
    }
  },
  // computed: {
  //   showTableData () {
  //     console.log(this.tableData);
  //     if (this.tableData.length == 0) return []
  //     return this.tableData.map(item => {
  //       return {
  //         id: item.id,
  //         name: item.name,
  //         number: item.number,
  //         company: item.company ? item.company.name : "",
  //         companyId: item.companyId,
  //         department: item.department ? item.department.name : "",
  //         deptId: item.department ? item.department.id : "",
  //         area: item.area.name,
  //         areaId: item.area.id,
  //         address: item.address,
  //         sysUser: item.sysUser ? item.sysUser.nickName : "",
  //         userId: item.sysUser ? item.sysUser.id : "",
  //         sysUserMobile: item.sysUser ? item.sysUser.mobile : "",
  //       }
  //     })
  //   }
  // },
  watch: {
    //------监听页面搜索框中值的变化----------
    "queryForm.query.areaId": {
      // 所选择地区发生改变
      async handler (newValue, oldValue) {
        console.log(newValue);
        // 根据地区，获得该地区的公司
        if (!newValue){
            // 清空 公司，部门
            this.queryForm.query.companyId = ''
            this.queryForm.query.deptId = ''
            this.search_companyList = []
            this.search_departmentList = []
          return
        } 
          
        const data = await getComByAreaId(newValue)
        console.log(data);
        this.search_companyList = data.data
        // 清空公司和部门
        if (this.isFirstEdit) return
        this.queryForm.query.companyId = ''
        this.queryForm.query.deptId = ''

      }
    },
    "queryForm.query.companyId": {
      // 所选择公司发生改变时
      async handler (newValue, oldValue) {
        console.log(newValue);
        // 根据公司，获得该公司的部门
        if (!newValue){
            // 清空 公司，部门
            this.queryForm.query.deptId = ''
            this.search_departmentList = []
          return
        }
        const data = await getDepartByComId(newValue)
        console.log(data);
        this.search_departmentList = data.data

        if (this.isFirstEdit) return
        this.queryForm.query.deptId = ''
      }

    },
    "queryForm.query.deptId": {
      // 所选择部门发生改变时
      async handler (newValue, oldValue) {
        console.log(newValue);
        // 根据部门，获得该部门所有人
         if (!newValue){
          return
        } 

        const data = await getPeopleByDepartId(newValue)
        console.log(data);
        this.search_principalList = data.data
      }

    },

    // ------监听弹出框中值的变化-----------
    "addForm.areaId": {
      // 所选择地区发生改变
      async handler (newValue, oldValue) {
        console.log(newValue);
        // 根据地区，获得该地区的公司
        if (!newValue){
            // 清空 公司，部门
            this.addForm.companyId = ''
            this.addForm.deptId = ''
            this.companyList = []
            this.departmentList = []
             this.addForm.userId = ''
            this.principalList = []
          return
        } 

        const data = await getComByAreaId(newValue)
        console.log(data);
        this.companyList = data.data

        if (this.isFirstEdit) return

        this.addForm.companyId = ''
        this.addForm.deptId = ''

      }

    },
    "addForm.companyId": {
      // 所选择公司发生改变时
      async handler (newValue, oldValue) {
        console.log(newValue);
        // 根据公司，获得该公司的部门
          if (!newValue){
            // 清空 公司，部门
            this.addForm.deptId = ''
            this.departmentList = []
            this.addForm.userId = ''
            this.principalList = []
          return
        } 
        const data = await getDepartByComId(newValue)
        console.log(data);
        this.departmentList = data.data

        //  公司 选择发生变化时，获得该公司所有的人，做为机房负责人的候选
        const ret = await getAllComUser(newValue);
        console.log(ret);
        if (ret.code == 20000) {
          this.principalList = ret.data
        }

        if (this.isFirstEdit) return
        this.addForm.deptId = ''
        this.addForm.userId = ''


      }

    },
    // "addForm.deptId": {
    //   // 所选择部门发生改变时
    //   async handler (newValue, oldValue) {
    //     console.log(newValue);
    //     // 根据部门，获得该部门所有人
    //     if (!newValue) return
    //     console.log(newValue);

    //     const data = await getPeopleByDepartId(newValue)
    //     console.log(data);
    //     this.principalList = data.data
    //     if(this.isFirstEdit) return

    //     this.addForm.userId = ''
    //   }

    // }
  },
  //方法集合",
  methods: {
    areaChange () {

      this.$refs.addFormRef.validateField('number');

    },
    cancelDialog () {
      this.addDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    // 搜索
    search () {
      this.multipleSelection = [];
      this.queryForm.page.current = 1;
      this.init();
    },
    // 重置
    reSet () {
      this.multipleSelection = [];
      this.queryForm = this.$options.data().queryForm;
      // 清空已经有的 公司列表 和 部门 列表
      this.companyList = []
      this.search_companyList = []
      this.departmentList = []
      this.search_departmentList = []
      this.init();
    },
    // 获取列表
    async init () {
      const { data } = await queryComputerRoom(this.queryForm);
      console.log(data);
      // console.log(JSON.stringify(data));
      this.tableData = data.records;
      this.total = data.total;
      // 获得所有地址的信息
      this.getAreaInfo();
    },
    async getCompanyList () {
      const data = await getCompanyList();
      this.companyList = data;
    },
    async getDepartmentList () {
      const data = await getDepartmentList();
      this.departmentList = data;
    },

    async getAreaInfo () {
      // 如果已经有地址信息了，就不再获取
      if (this.areaList.length > 0) return
      const data = await getAreaList();
      this.areaList = data.data;
      this.search_areaList = data.data
    },

    //跳转至视图
    goTuopu (row) {
      let destCI = this.ciRoomList.find(item => {
        return item.roomid == row.id
      })
      console.log(destCI);
      if (destCI == undefined) {
        this.$msg({
          type: 'warn',
          message: '所选机房没有视图'
        })
        return
      }

      destCI.type = 0

      this.$router.push({
        name: 'roomCIName',
        params: destCI
      })

      // this.$router.push({ name: 'roomListPrevies', params: { id: row.id, type: 'room' } });
    },
    // 改变页大小
    handleSizeChange (size) {
      this.queryForm.page.size = size;
      this.init();
    },
    // 改变页码
    handleCurrentChange (index) {
      this.current = index
      this.init();
    },
    saveRoom () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        if (!this.addForm.id) {
          // 添加机房
          const data = await doAdd(this.addForm);
          console.log(data);
          if (data.code == -1) {
            this.$message({
              type: 'warning',
              message: '机房名称已存在,不可重复',
            });
            return;
          } else if (data.code == 20000) {
            this.$message({
              type: 'success',
              message: '添加成功',
            });
          }

        } else {
          const data = await doEdit(this.addForm);
          if (data.code == -1) {
            this.$message({
              type: 'warning',
              message: '机房名称已存在,不可重复',
            });
            return;
          }
        }
        this.addDialogClosed()
        this.init();
      })
    },
    deleteRoom (row) {

      console.log(row);

      this.$confirm('此操作将删除该机房, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let ret = await doDelete([row.id]);

          if (ret.code == 20000) {

            let type = ''
            if (ret.data || ret.message.indexOf('成功') != -1) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }
            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            this.init()


          }

        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 批量删除
    catchDelete () {
      this.$confirm('此操作将删除所选机房, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let list = [];
          for (let i = 0; i < this.multipleSelection.length; i++) {
            list.push(this.multipleSelection[i].id)
          }
          // for(let i in list){
          //   console.log(list[i])
          // }
          let ret = await doDelete(list);
          if (ret.code == 20000) {

            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }
            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.multipleSelection.length == this.tableData.length) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            this.init()


          }

        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    editRoom (row) {
      if (row) {
        console.log(JSON.stringify(row));
        console.log(JSON.stringify(this.addForm));

        Object.assign(this.addForm, row);

        // 缓存当前的 公司 、 地区 、 编号 
        this.cacheNumberAreaId = {
          number: this.addForm.number,
          areaId: this.addForm.areaId,
          companyId: this.addForm.companyId,
        }

        this.formTitle = '修改机房信息';
        this.isFirstEdit = true

        // 下面这句话，有BUG 
        //  整体查询到的管理员，和根据部门查到的管理员，不是一个人。
        // this.addForm.userId = this.addForm.sysUser.nickName

      } else {
        this.formTitle = '添加机房';

        // 清空下拉区
        this.companyList = []
        this.departmentList = []
        this.principalList = []

      }
      this.multipleSelection = [];
      this.addDialogVisible = true;

      setTimeout(() => {
        this.isFirstEdit = false
      }, 2000);

    },
    addDialogClosed () {
      this.addForm = this.$options.data().addForm;
      this.addDialogVisible = false;
      this.$refs.addFormRef.resetFields()

      // this.companyList = []
      // this.departmentList = []
      // this.principalList = []
    },

    // 获得有视图的主机列表
    async getCiRoomList () {
      const ret = await getCIList({
        query: {
          name: '',
          type: 0
        },
        page: {
          current: 1,
          size: 10000
        }
      })
      if (ret.code == 20000) {

        let ciList = ret.data
        console.log(ciList);

        this.ciRoomList = []
        // 根据视图列表，获得有 视图的 机房列表
        for (let i = 0; i < ciList.length; i++) {
          let nodeList = ciList[i].nodeList // nodeList 中只有一个是机房

          for (let node of nodeList) {
            if (node.nodeType == 'room') {
              this.ciRoomList.push({
                roomid: node.viewData.id, // 机房ID
                roomName: node.viewData.name,
                ciId: ciList[i].id, // 视图ID
                ciName: ciList[i].name, // 视图名字
                ciName2: ciList[i].ciName, // 视图名字

              })

            }

          }
        }

        console.log(this.ciRoomList);
      }
    },
  },

  //生命周期 - 创建之前",数据模型未加载,方法未加载,html模板未加载
  beforeCreate () { },

  //生命周期 - 创建完成（可以访问当前this实例）",数据模型已加载，方法已加载,html模板已加载,html模板未渲染
  created () {
    this.init();

    this.getCiRoomList();


  },
  //生命周期 - 挂载完成（可以访问DOM元素）",html模板已渲染
  mounted () { },
}
</script>

<style lang='scss' scoped>
.el-select {
  width: 100% !important;
}
</style>
